package com.google.sydym6.logic.database;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.google.sydym6.R;
import com.google.sydym6.logic.database.data.IRadioData;
import com.google.sydym6.logic.database.data.RadioData;
import com.google.sydym6.logic.utils.ResourceUtils;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;


public class RadioDAO implements IRadioDAO{
	Set<IRadioData> radioDataSet;
	ITableWorker tableWorker;
	
	Context context;
	
	public RadioDAO(Context context) {
		radioDataSet = new HashSet<IRadioData>();
		this.context = context;
		TableFactory.create(context);
	}

	@Override
	public List<IRadioData> getFavourites() {
		tableWorker = TableFactory.getTable(DBConstants.RADIO_TABLE);
		Cursor cursor = tableWorker.select(new String[] {DBConstants.RADIO_FAVOURITE}, new String[] {"true"});
		cursor.moveToFirst();
		
		return getListByCursor(cursor);
	}

	@Override
	public List<IRadioData> getCatalog() {
		tableWorker = TableFactory.getTable(DBConstants.RADIO_TABLE);
		Cursor cursor = tableWorker.selectAll();
		cursor.moveToFirst();
		
		return getListByCursor(cursor);
	}

	private List<IRadioData> getListByCursor(Cursor cursor) {
		List<IRadioData> radioDataList = new ArrayList<IRadioData>();
		IRadioData instance;
		for(int i = 0; i < cursor.getCount(); i++) {
			 instance = new RadioData();
			 
			 instance.setId(Long.parseLong(cursor.getString(cursor.getColumnIndex(DBConstants.RADIO_ID))));
			 instance.setTitle(cursor.getString(cursor.getColumnIndex(DBConstants.RADIO_NAME)));
			 instance.setUrl(cursor.getString(cursor.getColumnIndex(DBConstants.RADIO_URL)));
			 instance.setFavourite(Boolean.parseBoolean(cursor.getString(cursor.getColumnIndex(DBConstants.RADIO_FAVOURITE))));
			 //Log.v("database", "Favourite: " + cursor.getString(cursor.getColumnIndex(DBConstants.RADIO_FAVOURITE)));
			 instance.setTalk(Boolean.parseBoolean(cursor.getString(cursor.getColumnIndex(DBConstants.RADIO_TALK))));
			 Log.v("database", "Cover art: " + cursor.getColumnIndex(DBConstants.RADIO_COVER_ART));
			 instance.setCover(ResourceUtils.getResourceId(cursor.getString(cursor.getColumnIndex(DBConstants.RADIO_COVER_ART)), context, R.drawable.class));
			 
			 radioDataSet.add(instance);
			 radioDataList.add(instance);
			 
			 cursor.moveToNext();
		}
		
		return radioDataList;
	}

	@Override
	public Set<IRadioData> getRadioData() {
		return radioDataSet;
	}
}
